<?php

defined('SYSPATH') or die('No direct script access.');

class Controller_Project2 extends Controller {

	public function before() {
		parent::before();
		$this->_json = FALSE;
		$this->_short = FALSE;
		$this->_data['controller'] = $this->request->controller();
		$this->_data['action'] = $this->request->action();
		$this->_data['itemid'] = $this->request->param('itemid',NULL);
	}

	public function after() {
		if ($this->_json === TRUE) {
			$this->response->headers('Content-Type', 'text/json charset=utf-8');
			$this->_body = json_encode($this->_body);
		}
		elseif ($this->_short === FALSE) {
			$this->_body = View::factory($this->_data['controller'].'/blocks/header_bs', $this->_data) .
				View::factory($this->_data['controller'].'/blocks/header_bs_menu', $this->_data) .
				$this->_body .
				View::factory($this->_data['controller'].'/blocks/footer_bs');
		}
		$this->response->body($this->_body);
		parent::after();
	}

	public function action_main(){
		$data = $this->request->query();
		$cian = Ads::instance();
		//$data = $cian->query('http://www.cian.ru/cat.php?deal_type=1&obl_id=1&city[0]=1')->parse();
		//$cian->write($data);
		//echo $cian->read(11359831)->get('city');
		//$ads = $cian->read(11359831)->as_array();
		//print_r($ads);
		//echo Request::$user_agent;
			$this->_data['adslist'] = $cian->readnew(100);//View::factory($this->_data['controller'].'/pages/'.$this->_data['action'], $this->_data);
			$this->_data['title'] = 'Список';
			$this->_body = $page.View::factory($this->_data['controller'].'/pages/'.$this->_data['action'], $this->_data);
	}

	public function action_count(){
		$cian = Ads::instance();
		$this->_body = 'Текущее количество: '.$cian->count();
		$cianrds = Ads::instance('cianrds');
		$this->_body .= '<br>Текущее количество в REDIS: '.$cianrds->count();
	}

	public function action_cian() {
		$html = $this->query('http://www.cian.ru/cat.php?deal_type=1&obl_id=1&city[0]=1&totime=600'/*, TRUE*/);// add time in url
		//$html = $this->query('http://a.lidocs.ru/login', TRUE);
		$document = phpQuery::newDocument($html);
		$rows = pq("table.cat tr[id^='tr_']");
		foreach ($rows as $row) {
			pq($row)->find("br")->replaceWith(" ");
			pq($row)->find("div.complaint")->replaceWith("");
			pq($row)->find("span.np")->replaceWith("");
			$id = str_replace('tr_','',pq($row)->attr('id'));
			$data[$id]['distance'] = pq($row)->find("td[id$='_metro']")->clone()->children()->remove()->end()->text();
			for($i=0;$i<pq($row)->find("td[id$='_metro'] a")->length;$i++){
				$_text = pq($row)->find("td[id$='_metro'] a")->eq($i)->text();
				$_href = str_replace('/cat.php?deal_type=1&','',pq($row)->find("td[id$='_metro'] a")->eq($i)->attr('href'));
				if (preg_match('`^obl_id=(\d+)$`si',$_href)){
					$data[$id]['city'] = $_text;
				}
				elseif (preg_match('`^obl_id=(\d+)&street\[0\]=(\d+)$`si',$_href)){
					$data[$id]['street'] = $_text;
				}
				elseif (preg_match('`^obl_id=(\d+)&street\[0\]=(\d+)&house=(\d+)&ohn=(\d+)$`si',$_href)){
					$data[$id]['house'] = $_text;
				}
				elseif (preg_match('`^obl_id=(\d+)&metro\[0\]=(\d+)$`si',$_href)){
					$data[$id]['metro'] = $_text;
				}
			}
			$data[$id]['room'] = pq($row)->find("td[id$='_room'] a")->text();
			$data[$id]['rooms'] = pq($row)->find("td[id$='_rooms']")->text();
			$data[$id]['price'] = pq($row)->find("td[id$='_price']")->text();
			$data[$id]['floor'] = pq($row)->find("td[id$='_floor']")->text();
			$data[$id]['dopsved'] = pq($row)->find("td[id$='_dopsved']")->text();
			$data[$id]['com'] = pq($row)->find("td[id$='_com']")->text();
			$data[$id]['contacts'] = pq($row)->find("td[id$='_contacts'] a")->text();
			$data[$id]['datetime'] = pq($row)->find("td[id$='_comment'] span[id^='added_']")->text();
			$data[$id]['comment'] = pq($row)->find("td[id$='_comment']")->clone()->children()->remove()->end()->text();
		}
		foreach ($data as $id => &$arr) {
			foreach ($arr as &$str) {
				$str = preg_replace('"\s+"si', ' ', trim(str_replace('&nbsp;', ' ', $str)));
			}
		}
		$this->_body = '<pre>' . print_r($data, TRUE);
	}

	public function action_irr() {
		$html = $this->query('http://irr.ru/real-estate/rent/search/list=list/page_len60/', TRUE);
		//exit(); //$html = $this->query('http://a.lidocs.ru/login', TRUE);
		$document = phpQuery::newDocument($html);
		$rows = pq("div.add_list.add_type4");
		foreach ($rows as $id => $row) {
			pq($row)->find("br")->replaceWith(" ");
			$data[$id]['datetime'] = pq($row)->find("p.adv_data")->eq(0)->text(); //.' - ';
			$data[$id]['comment'] = pq($row)->find("div.pic_wrap a img")->eq(0)->attr('alt'); //.' - ';
			$data[$id]['city'] = pq($row)->find("div.add_info div.main_props a.add_title")->eq(0)->text(); //.' - ';
			$data[$id]['metro'] = pq($row)->find("div.add_info div.main_props div.placed")->eq(0)->text(); //.' - ';
			$data[$id]['room'] = pq($row)->find("div.add_info div.main_props div.flat_prop div.flat_p")->eq(0)->text(); //.' - ';
			$data[$id]['square'] = pq($row)->find("div.add_info div.main_props div.flat_prop div.flat_p")->eq(1)->text(); //.' - ';
			$data[$id]['etage'] = pq($row)->find("div.add_info div.main_props div.flat_prop div.flat_p")->eq(2)->text(); //.' - ';
			$data[$id]['tag'] = pq($row)->find("div.add_info div.main_props div.tags")->eq(0)->text(); //.' - ';
			pq($row)->find("div.add_info div.right_block div.add_cost span.rubl")->replaceWith("руб ");
			$data[$id]['cost'] = pq($row)->find("div.add_info div.right_block div.add_cost")->eq(0)->text(); //.' - ';
			//echo $data[$id]['metro'] = pq($row)->find("div.add_info div.main_props div.placed")->eq(0)->text();
			//echo $data[$id]['metro'] = pq($row)->find("div.add_info div.main_props div.placed")->eq(0)->text();
			//echo $data[$id]['datetime'] = pq($row)->find("p.adv_data")->eq(0)->text();
			//echo $data[$id]['datetime'] = pq($row)->find("p.adv_data")->eq(0)->text();
			//echo '<br>'.PHP_EOL;




			/*
			  $data[$id]['distance'] = pq($row)->find("td[id$='_metro']")->clone()->children()->remove()->end()->text();
			  $data[$id]['city'] = pq($row)->find("td[id$='_metro'] a")->eq(0)->text();
			  $data[$id]['street'] = pq($row)->find("td[id$='_metro'] a")->eq(1)->text();
			  $data[$id]['house'] = pq($row)->find("td[id$='_metro'] a")->eq(2)->text();
			  $data[$id]['metro'] = pq($row)->find("td[id$='_metro'] a")->eq(3)->text();
			  $data[$id]['room'] = pq($row)->find("td[id$='_room'] a")->text();
			  $data[$id]['rooms'] = pq($row)->find("td[id$='_rooms']")->text();
			  $data[$id]['price'] = pq($row)->find("td[id$='_price']")->text();
			  $data[$id]['floor'] = pq($row)->find("td[id$='_floor']")->text();
			  $data[$id]['dopsved'] = pq($row)->find("td[id$='_dopsved']")->text();
			  $data[$id]['com'] = pq($row)->find("td[id$='_com']")->text();
			  $data[$id]['contacts'] = pq($row)->find("td[id$='_contacts'] a")->text();
			  $data[$id]['datetime'] = pq($row)->find("td[id$='_comment'] span[id^='added_']")->text();
			  $data[$id]['comment'] = pq($row)->find("td[id$='_comment']")->clone()->children()->remove()->end()->text();
			 *
			 */
		}
		foreach ($data as $id => &$arr) {
			foreach ($arr as &$str) {
				$str = preg_replace('"\s+"si', ' ', trim(str_replace('&nbsp;', ' ', $str)));
			}
		}
		$this->_body = '<pre>' . print_r($data, TRUE);
	}

	private function query($url, $cache = FALSE) {

		if (isset(Cache::$instances['redis'])) {
			$redis = Cache::$instances['redis'];
		}
		else {
			$redis = Cache::instance('redis');
		}
		$data = $redis->get(md5($url), FALSE);
		if (!empty($data) AND $cache == TRUE) {
			return $data;
		}
		else {
			$request = Request::factory($url)
					->method(Request::GET);
			$request->client()
					->options(array(
						CURLOPT_SSL_VERIFYPEER => FALSE,
						CURLOPT_USERAGENT => Request::$user_agent,
						CURLOPT_HTTPHEADER => array(
							'Accept-Encoding:gzip,deflate,sdch',
							'Accept-Language:ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4',
						),
						CURLOPT_FOLLOWLOCATION => TRUE,
						CURLOPT_COOKIEFILE => APPPATH . "config/cookie.file",
						CURLOPT_COOKIEJAR => APPPATH . "config/cookie.file",
			));
			$response = $request->execute();
			$data = $response->body();
			$redis->set(md5($url), $data, 3600);
		}
		return $data;
	}

	public function action_test(){
		$cianrds = Ads::instance('cianrds');
		$data = $cianrds->query('http://www.cian.ru/cat.php?deal_type=1&obl_id=1&city[0]=1&totime=600',TRUE)->parse();
		$cianrds->write($data);
	}

	public function action_getresult(){
		$this->_short = TRUE;
		$cianrds = Ads::instance('cianrds');
		$ads = &$cianrds->search($_POST);
		foreach($ads as &$item){
			$adslist[] = View::factory($this->_data['controller'].'/blocks/ads/list',array('ads'=>$item));
		}
		echo 'exec time:'.(microtime(true)-TIMESTART).'<br>'.count($adslist).'<br>';
		$this->_body = implode('',$adslist);
	}

}

// End Project2
